<template>
  <!--物流地图组件 实现路线规划的核心组件，负责初始化地图、规划路线、创建动画等功能 -->
  <div class="logistics-map-container">
    <div v-if="loading" class="loading">加载地图中...</div>
    <div v-if="error" class="error">{{ error }}<br><small>请确保您的网络连接正常并允许访问高德地图</small></div>

    <div id="logistics-map" class="map-container"></div>

    <div v-if="showLogisticsInfo" class="logistics-info">
      <div class="logistics-status">
        <div class="status-icon" :class="statusClass"></div>
        <div class="status-text">{{ statusText }}</div>
      </div>

      <div class="logistics-details">
        <div class="detail-item">
          <div class="detail-label">预计到达:</div>
          <div class="detail-value">{{ estimatedArrival }}</div>
        </div>
        <div class="detail-item">
          <div class="detail-label">当前位置:</div>
          <div class="detail-value">{{ currentLocation }}</div>
        </div>
      </div>

      <div class="logistics-control">
        <button v-if="!isPlayingAnimation" @click="startAnimation" class="control-btn play-btn">
          开始模拟
        </button>
        <button v-else @click="stopAnimation" class="control-btn stop-btn">
          停止模拟
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, computed } from 'vue';
import { initAMap, createLogisticsRoute, planLogisticsRoute, geocodeAddress, regeocode } from '../../utils/amapUtils';
import AMapLoader from '@amap/amap-jsapi-loader';

export default {
  name: 'LogisticsMap',
  props: {
    // 订单信息
    order: {
      type: Object,
      required: true
    },
    // 发货地址
    shippingAddress: {
      type: String,
      default: ''
    },
    // 收货地址
    receivingAddress: {
      type: String,
      default: ''
    },
    // 物流状态 (0: 未发货, 1: 已发货在途, 2: 已送达, 3: 已签收)
    logisticsStatus: {
      type: Number,
      default: 0
    },
    // 物流公司
    logisticsCompany: {
      type: String,
      default: ''
    },
    // 物流单号
    logisticsNumber: {
      type: String,
      default: ''
    },
    // 预计到达时间
    expectedDeliveryTime: {
      type: String,
      default: ''
    }
  },
  setup(props) {
    const loading = ref(true);
    const error = ref('');
    const mapInstance = ref(null);
    const routeInstance = ref(null);
    const currentLocation = ref('');
    const isPlayingAnimation = ref(false);
    const showLogisticsInfo = ref(false);

    // 计算状态文本
    const statusText = computed(() => {
      const statusMap = {
        0: '等待发货',
        1: '运输中',
        2: '已送达',
        3: '已签收'
      };
      return statusMap[props.logisticsStatus] || '未知状态';
    });

    // 计算状态样式
    const statusClass = computed(() => {
      const classMap = {
        0: 'waiting',
        1: 'delivering',
        2: 'arrived',
        3: 'signed'
      };
      return classMap[props.logisticsStatus] || '';
    });

    // 计算预计到达时间
    const estimatedArrival = computed(() => {
      return props.expectedDeliveryTime || '暂无信息';
    });

    // 初始化地图
    const initMap = async () => {
      try {
        loading.value = true;

        // 先检查地图容器元素是否存在
        if (!document.getElementById('logistics-map')) {
          error.value = '地图容器不存在，请检查页面结构';
          loading.value = false;
          return;
        }

        mapInstance.value = await initAMap('logistics-map');
        loading.value = false;
        showLogisticsInfo.value = true;

        // 如果有发货地址和收货地址，则规划路线
        if (props.shippingAddress && props.receivingAddress && props.logisticsStatus > 0) {
          await planRoute();
        }
      } catch (e) {
        loading.value = false;

        // 根据错误类型显示不同的错误信息
        if (e.message && e.message.includes('AMap')) {
          error.value = '高德地图API加载失败，请检查您的网络连接并刷新页面';
        } else {
          error.value = '地图加载失败，请刷新重试';
        }

        console.error('地图初始化失败:', e);

        // 在出错时更新当前位置信息，显示静态信息
        if (props.shippingAddress && props.receivingAddress) {
          currentLocation.value = `${props.shippingAddress} 至 ${props.receivingAddress}`;
        }
      }
    };

    // 规划路线
    const planRoute = async () => {
      try {
        if (!mapInstance.value) {
          console.error('地图实例不存在，无法规划路线');
          return;
        }

        // 获取起点和终点坐标
        let startPos, endPos;

        // 优先使用地址进行坐标转换
        try {
          startPos = await geocodeAddress(props.shippingAddress);
          endPos = await geocodeAddress(props.receivingAddress);

          console.log('成功从地址获取坐标:', {
            shipping: startPos,
            receiving: endPos,
            receivingAddress: props.receivingAddress
          });
        } catch (e) {
          console.warn('地址转坐标失败，尝试使用提供的坐标:', e);

          // 如果物流信息中包含坐标，则作为备选使用
          if (props.order && props.order.shippingCoords) {
            startPos = props.order.shippingCoords;
            endPos = props.order.receivingCoords;
          } else {
            console.error('找不到可用坐标，使用默认坐标');
            // 使用默认坐标
            startPos = [121.613939, 31.207767]; // 上海
            endPos = [116.483371, 39.941752]; // 北京
          }
        }

        // 开始规划路线
        try {
          planLogisticsRoute(mapInstance.value, startPos, endPos, async (result) => {
            if (result.status === 'success' && result.path && result.path.length) {
              // 创建物流路线
              try {
                routeInstance.value = await createLogisticsRoute(
                  mapInstance.value,
                  result.path,
                  {
                    markerStyle: {
                      content: `<div class="logistics-marker">${props.logisticsCompany.charAt(0) || '配'}</div>`,
                      offset: [-15, -30]
                    }
                  }
                );

                // 如果物流状态是运输中，则自动开始动画
                if (props.logisticsStatus === 1) {
                  startAnimation();
                }

                // 获取并显示当前位置信息
                updateCurrentLocation(result.path[0]);

                // 根据物流状态设置路线的显示进度
                if (props.logisticsStatus === 2 || props.logisticsStatus === 3) {
                  routeInstance.value.pathNavigator.moveToLast();
                  updateCurrentLocation(result.path[result.path.length - 1]);
                }
              } catch (e) {
                console.error('创建物流路线失败:', e);
                error.value = '路线创建失败，但您仍可以查看物流信息';

                // 即使路线失败也显示地点信息
                currentLocation.value = `${props.shippingAddress} → ${props.receivingAddress}`;
              }
            } else {
              error.value = '路线规划失败，但您仍可以查看物流信息';
              // 即使规划失败也显示地点信息
              currentLocation.value = `${props.shippingAddress} → ${props.receivingAddress}`;

              // 尝试直接在地图上添加起点和终点标记
              try {
                // 使用window.AMap而不是重新加载AMapLoader
                const startMarker = new window.AMap.Marker({
                  map: mapInstance.value,
                  position: startPos,
                  content: '<div class="logistics-marker logistics-start">始</div>',
                  offset: new window.AMap.Pixel(-15, -30),
                  zIndex: 120
                });

                const endMarker = new window.AMap.Marker({
                  map: mapInstance.value,
                  position: endPos,
                  content: '<div class="logistics-marker logistics-end">终</div>',
                  offset: new window.AMap.Pixel(-15, -30),
                  zIndex: 110
                });

                // 设置地图视野以包含两个点
                const bounds = new window.AMap.Bounds(
                  [Math.min(startPos[0], endPos[0]), Math.min(startPos[1], endPos[1])],
                  [Math.max(startPos[0], endPos[0]), Math.max(startPos[1], endPos[1])]
                );
                mapInstance.value.setBounds(bounds);
              } catch (e) {
                console.error('添加备用标记失败:', e);
              }
            }
          });
        } catch (e) {
          console.error('路线规划调用失败:', e);
          error.value = '路线规划失败，但您仍可以查看物流信息';
          currentLocation.value = `${props.shippingAddress} → ${props.receivingAddress}`;
        }
      } catch (e) {
        error.value = '路线规划失败，请检查地址信息是否正确';
        console.error('路线规划失败:', e);
      }
    };

    // 开始动画
    const startAnimation = () => {
      if (routeInstance.value && !isPlayingAnimation.value) {
        routeInstance.value.start();
        isPlayingAnimation.value = true;

        // 监听位置变化更新当前位置
        routeInstance.value.pathNavigator.on('move', (e) => {
          updateCurrentLocation(e.target.getPosition());
        });

        // 监听到达终点
        routeInstance.value.pathNavigator.on('end', () => {
          isPlayingAnimation.value = false;
        });
      }
    };

    // 停止动画
    const stopAnimation = () => {
      if (routeInstance.value && isPlayingAnimation.value) {
        routeInstance.value.stop();
        isPlayingAnimation.value = false;
      }
    };

    // 更新当前位置信息
    const updateCurrentLocation = async (position) => {
      try {
        if (!position) {
          currentLocation.value = '未知位置';
          return;
        }

        // 确保position是有效的
        if ((!Array.isArray(position) && (!position.lng && !position.lat))) {
          currentLocation.value = `${props.shippingAddress} → ${props.receivingAddress}`;
          return;
        }

        try {
          // 获取位置的地址描述
          const result = await regeocode([position.lng || position[0], position.lat || position[1]]);
          // 如果没有格式化地址，则使用备用信息
          if (!result || !result.formattedAddress) {
            // 使用备用信息
            if (props.logisticsStatus === 0) {
              currentLocation.value = props.shippingAddress || '发货地';
            } else if (props.logisticsStatus >= 2) {
              currentLocation.value = props.receivingAddress || '收货地';
            } else {
              currentLocation.value = `${props.shippingAddress || '发货地'} → ${props.receivingAddress || '收货地'}`;
            }
          } else {
            currentLocation.value = result.formattedAddress;
          }
        } catch (geoError) {
          console.warn('地址解析失败，使用备用信息:', geoError);
          // 使用物流状态来决定显示什么
          if (props.logisticsStatus === 0) {
            currentLocation.value = props.shippingAddress || '发货地';
          } else if (props.logisticsStatus >= 2) {
            currentLocation.value = props.receivingAddress || '收货地';
          } else {
            currentLocation.value = `在途中 (${props.shippingAddress || '发货地'} → ${props.receivingAddress || '收货地'})`;
          }
        }
      } catch (e) {
        console.error('获取位置信息失败:', e);
        currentLocation.value = `${props.shippingAddress || '发货地'} → ${props.receivingAddress || '收货地'}`;
      }
    };

    // 组件挂载时初始化地图
    onMounted(() => {
      initMap();
    });

    // 组件卸载时清理资源
    onUnmounted(() => {
      if (routeInstance.value) {
        routeInstance.value.stop();
      }

      // 清理地图实例
      if (mapInstance.value) {
        mapInstance.value = null;
      }
    });

    return {
      loading,
      error,
      currentLocation,
      isPlayingAnimation,
      showLogisticsInfo,
      statusText,
      statusClass,
      estimatedArrival,
      startAnimation,
      stopAnimation
    };
  }
}
</script>

<style scoped>
.logistics-map-container {
  width: 100%;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  position: relative;
  display: flex;
  flex-direction: column;
}

.map-container {
  width: 100%;
  height: 500px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.loading,
.error {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.8);
  z-index: 10;
}

.error {
  color: #f56c6c;
}

.logistics-info {
  padding: 16px;
  background-color: #fff;
  border-top: 1px solid #eee;
}

.logistics-status {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.status-icon {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  margin-right: 8px;
}

.status-icon.waiting {
  background-color: #909399;
}

.status-icon.delivering {
  background-color: #409eff;
}

.status-icon.arrived {
  background-color: #67c23a;
}

.status-icon.signed {
  background-color: #67c23a;
}

.status-text {
  font-weight: bold;
  font-size: 16px;
}

.logistics-details {
  margin-bottom: 16px;
}

.detail-item {
  display: flex;
  margin-bottom: 8px;
}

.detail-label {
  width: 80px;
  color: #606266;
}

.detail-value {
  flex: 1;
  color: #303133;
}

.logistics-control {
  display: flex;
  justify-content: center;
}

.control-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.play-btn {
  background-color: #409eff;
  color: white;
}

.play-btn:hover {
  background-color: #66b1ff;
}

.stop-btn {
  background-color: #f56c6c;
  color: white;
}

.stop-btn:hover {
  background-color: #f78989;
}

/* 自定义物流标记样式 */
:deep(.logistics-marker) {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  font-weight: bold;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
  color: white;
  font-size: 16px;
  border: 2px solid white;
}

:deep(.logistics-vehicle) {
  background-color: #409eff;
  animation: pulse 1.5s infinite;
  z-index: 200 !important;
}

:deep(.logistics-start) {
  background-color: #67c23a;
  font-size: 14px;
}

:deep(.logistics-end) {
  background-color: #f56c6c;
  font-size: 14px;
}

@keyframes pulse {
  0% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0.7);
  }

  70% {
    transform: scale(1.1);
    box-shadow: 0 0 0 10px rgba(64, 158, 255, 0);
  }

  100% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0);
  }
}
</style>